#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
商品图片管理工具
用于管理商品图片的上传、重命名和删除
"""

import os
import shutil
import json
from pathlib import Path

class ProductImageManager:
    def __init__(self):
        self.images_dir = Path(__file__).parent
        self.supported_formats = ['.jpg', '.jpeg', '.png', '.webp', '.gif']
    
    def add_product_image(self, product_id, image_path, image_type='main'):
        """
        添加商品图片
        
        Args:
            product_id: 商品ID
            image_path: 图片文件路径
            image_type: 图片类型 ('main' 或 'extra')
        """
        try:
            # 检查源文件是否存在
            if not os.path.exists(image_path):
                return False, f"源文件不存在: {image_path}"
            
            # 获取文件扩展名
            ext = Path(image_path).suffix.lower()
            if ext not in self.supported_formats:
                return False, f"不支持的文件格式: {ext}"
            
            # 生成目标文件名（保持原始格式）
            if image_type == 'main':
                target_name = f"{product_id}{ext}"
            else:
                # 查找下一个可用的序号（保持原始格式）
                counter = 2
                while True:
                    target_name = f"{product_id}_{counter}{ext}"
                    if not (self.images_dir / target_name).exists():
                        break
                    counter += 1
            
            target_path = self.images_dir / target_name
            
            # 复制文件
            shutil.copy2(image_path, target_path)
            
            return True, f"图片已添加: {target_name}"
            
        except Exception as e:
            return False, f"添加图片失败: {str(e)}"
    
    def remove_product_image(self, product_id, image_type='all'):
        """
        删除商品图片
        
        Args:
            product_id: 商品ID
            image_type: 删除类型 ('main', 'all', 或具体序号如 '2')
        """
        try:
            removed_files = []
            
            if image_type in ['main', 'all']:
                # 删除主图（支持所有格式）
                for ext in self.supported_formats:
                    main_image = f"{product_id}{ext}"
                    main_path = self.images_dir / main_image
                    if main_path.exists():
                        main_path.unlink()
                        removed_files.append(main_image)
                        break  # 只删除找到的第一个格式
            
            if image_type in ['all'] or (image_type.isdigit() and int(image_type) >= 2):
                # 删除所有额外图片或指定序号的图片（支持所有格式）
                for ext in self.supported_formats:
                    for file_path in self.images_dir.glob(f"{product_id}_*{ext}"):
                        if image_type == 'all' or (image_type.isdigit() and file_path.stem.endswith(f"_{image_type}")):
                            file_path.unlink()
                            removed_files.append(file_path.name)
            
            return True, f"已删除图片: {', '.join(removed_files)}"
            
        except Exception as e:
            return False, f"删除图片失败: {str(e)}"
    
    def list_product_images(self, product_id):
        """列出商品的所有图片"""
        images = []
        
        # 主图（支持所有格式）
        for ext in self.supported_formats:
            main_image = f"{product_id}{ext}"
            main_path = self.images_dir / main_image
            if main_path.exists():
                images.append({
                    'name': main_image,
                    'type': 'main',
                    'format': ext,
                    'path': f"images/products/{main_image}"
                })
                break  # 只列出找到的第一个格式
        
        # 额外图片（支持所有格式）
        for ext in self.supported_formats:
            for file_path in sorted(self.images_dir.glob(f"{product_id}_*{ext}")):
                images.append({
                    'name': file_path.name,
                    'type': 'extra',
                    'format': ext,
                    'path': f"images/products/{file_path.name}"
                })
        
        return images
    
    def get_image_info(self):
        """获取图片目录信息"""
        total_images = 0
        total_size = 0
        
        # 统计所有支持的图片格式
        for ext in self.supported_formats:
            images = list(self.images_dir.glob(f"*{ext}"))
            total_images += len(images)
            total_size += sum(f.stat().st_size for f in images)
        
        # 统计各格式的数量
        format_counts = {}
        for ext in self.supported_formats:
            count = len(list(self.images_dir.glob(f"*{ext}")))
            if count > 0:
                format_counts[ext] = count
        
        return {
            'total_images': total_images,
            'total_size_mb': round(total_size / (1024 * 1024), 2),
            'format_counts': format_counts,
            'directory': str(self.images_dir)
        }

def main():
    """命令行工具"""
    import sys
    
    manager = ProductImageManager()
    
    # 检查命令行参数
    if len(sys.argv) > 1:
        command = sys.argv[1].lower()
        
        if command == 'list':
            # 列出所有图片
            info = manager.get_image_info()
            print(f"图片目录: {info['directory']}")
            print(f"总图片数: {info['total_images']}")
            print(f"总大小: {info['total_size_mb']} MB")
            if info.get('format_counts'):
                print("格式分布:")
                for fmt, count in info['format_counts'].items():
                    print(f"  {fmt}: {count} 张")
            
            # 列出前20个图片文件
            images_dir = manager.images_dir
            if os.path.exists(images_dir):
                png_files = [f for f in os.listdir(images_dir) if f.endswith('.png')]
                png_files.sort()
                print(f"\n前20个图片文件:")
                for i, filename in enumerate(png_files[:20]):
                    print(f"  {i+1:2d}. {filename}")
                if len(png_files) > 20:
                    print(f"  ... 还有 {len(png_files) - 20} 个文件")
                    
        elif command == 'add' and len(sys.argv) >= 4:
            product_id = sys.argv[2]
            image_path = sys.argv[3]
            image_type = sys.argv[4] if len(sys.argv) > 4 else 'main'
            
            success, message = manager.add_product_image(product_id, image_path, image_type)
            print(f"{'成功' if success else '失败'}: {message}")
            
        elif command == 'remove' and len(sys.argv) >= 3:
            product_id = sys.argv[2]
            image_type = sys.argv[3] if len(sys.argv) > 3 else 'all'
            
            success, message = manager.remove_product_image(product_id, image_type)
            print(f"{'成功' if success else '失败'}: {message}")
            
        elif command == 'info':
            info = manager.get_image_info()
            print(f"图片目录信息:")
            print(f"  总图片数: {info['total_images']}")
            print(f"  总大小: {info['total_size_mb']} MB")
            print(f"  目录路径: {info['directory']}")
            if info.get('format_counts'):
                print(f"  格式分布:")
                for fmt, count in info['format_counts'].items():
                    print(f"    {fmt}: {count} 张")
                    
        elif command == '--help' or command == '-h':
            print("商品图片管理工具")
            print("=" * 50)
            print("用法:")
            print("  python3 image_manager.py list                    # 列出所有图片")
            print("  python3 image_manager.py add 商品ID 图片路径      # 添加图片")
            print("  python3 image_manager.py remove 商品ID           # 删除图片")
            print("  python3 image_manager.py info                    # 显示目录信息")
            print("  python3 image_manager.py                         # 交互模式")
        else:
            print("无效命令，使用 --help 查看帮助")
    else:
        # 交互模式
        print("商品图片管理工具")
        print("=" * 50)
        
        while True:
            print("\n选择操作:")
            print("1. 添加商品图片")
            print("2. 删除商品图片")
            print("3. 查看商品图片")
            print("4. 查看图片目录信息")
            print("5. 退出")
            
            try:
                choice = input("\n请输入选择 (1-5): ").strip()
                
                if choice == '1':
                    product_id = input("请输入商品ID: ").strip()
                    image_path = input("请输入图片文件路径: ").strip()
                    image_type = input("图片类型 (main/extra): ").strip() or 'main'
                    
                    success, message = manager.add_product_image(product_id, image_path, image_type)
                    print(f"{'成功' if success else '失败'}: {message}")
                
                elif choice == '2':
                    product_id = input("请输入商品ID: ").strip()
                    image_type = input("删除类型 (main/all/序号): ").strip() or 'all'
                    
                    success, message = manager.remove_product_image(product_id, image_type)
                    print(f"{'成功' if success else '失败'}: {message}")
                
                elif choice == '3':
                    product_id = input("请输入商品ID: ").strip()
                    images = manager.list_product_images(product_id)
                    
                    if images:
                        print(f"\n商品 {product_id} 的图片:")
                        for img in images:
                            print(f"  - {img['name']} ({img['type']})")
                    else:
                        print(f"商品 {product_id} 没有图片")
                
                elif choice == '4':
                    info = manager.get_image_info()
                    print(f"\n图片目录信息:")
                    print(f"  总图片数: {info['total_images']}")
                    print(f"  总大小: {info['total_size_mb']} MB")
                    print(f"  目录路径: {info['directory']}")
                    if info.get('format_counts'):
                        print(f"  格式分布:")
                        for fmt, count in info['format_counts'].items():
                            print(f"    {fmt}: {count} 张")
                
                elif choice == '5':
                    print("退出程序")
                    break
                
                else:
                    print("无效选择，请重新输入")
            except (EOFError, KeyboardInterrupt):
                print("\n\n程序已退出")
                break

if __name__ == "__main__":
    main()
